import React, { Component, useState } from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    ScrollView,
    DeviceEventEmitter,
    TextInput,
} from 'react-native';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import Constant from '../../utils/Constant'; //全局变量
import Header from '../../components/header';
import { ToastToUser } from '../../utils/CustomToast';
import Loading from '../../utils/Loading';
import NoData from '../../utils/NoData';
import RegionPickerView from '../../components/Tool/RegionAllPickerView';
import AndroidModule from "../../utils/AndroidConnent";
const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;

const colorsOptions = ['#ED542E', '#2CE454', '#2CE454', '#ff6600', '#ED542E'];
let navigation;
export default class BuyerSetLabelPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            preferences: '',
            showCityPicker: false,
            tempCity: "",
            brands: [],
            prices: [],
            sulations: [],
            filtersData: [],
            textNum: 0
        };
    }
    componentWillUnmount() {

        if (this.selectBrandResult) {
            this.selectBrandResult.remove();
        }

    }
    componentDidMount() {

        this.selectBrandResult = DeviceEventEmitter.addListener('selectBrandResult', (result) => {
            if (result && result.from === 'BuyerSetLabelPage') {
                this.formatBrand(result)
            }
        })
        this.getMyLabeldata()
    }
    //城市选择回调处理
    cityPickerData(item) {
        console.log("城市选择结果", item)
        this.setState({
            showCityPicker: false
        })
        let temp = this.state.filtersData
        temp.forEach((it, id) => {
            if (it.type ==='收车城市' ) {
                //写死类型
                let tagList = it.tagList
                let param = {
                    tagValueText: item.cityName,
                    tagValue: item.cityId,
                    selected: 1,
                }

                if(item.cityName === '不限'){
                    param = {
                        tagValueText: item.provinceName,
                        tagValue: item.provinceId,
                        selected: 1,
                    }
                }

                // 选择非全部后把去除
                tagList.forEach((it, id) => {
                    // 去除tagList里面tagValue为全部的
                    if(it.tagValueText == '不限'){
                        tagList.splice(id, 1)
                    }
                })
                let exsits= this.filterSameData(tagList, param)
                if (!exsits) {
                    tagList.push(param)
                }
            }
        })
        this.setState({
            filtersData:temp
        })
    }
    //多选去重，城市和品牌
    filterSameData(taglist, item) {
        let exsits = false
        taglist.forEach((it, id) => {
            if (it.tagValue == item.tagValue) {

                exsits= true
            }
        })

        return exsits
    }
    //获取我的标签数据
    getMyLabeldata() {
        if (this.Loading) {
            this.Loading.show()
        }
        let param = {
            buyerId: Constant.userInfo.buyerId,
        };

        HttpUtils.getRequest(HttpUrls.buyerSetLable, param)
            .then(result => {
                let data = result.data;
                if (data) {
                    console.log('getMerchantList:', data);
                    let temp = data.buyerTagList
                    temp.forEach((it, id) => {
                        if (it.type === '收车城市') {
                            if(it.tagList && it.tagList.length === 0){
                                it.tagList.push({
                                    tagValueText: "不限",
                                    tagValue: 0,
                                    selected: 1
                                })
                            }
                        }
                        if (it.type === '品牌车系') {
                            if(it.tagList && it.tagList.length === 0){
                                it.tagList.push({
                                    tagValueText: "不限",
                                    tagValue: 0,
                                    selected: 1
                                })
                            }
                        }
                    })
                    this.setState({
                        filtersData: temp,
                        preferences: data.preferences,
                        textNum: data.preferences.length
                    })
                } else {
                    ToastToUser(result.msg ? result.msg : result.message)
                }
            })
            .catch(error => { }).finally(e => {
            this.Loading.hide()
        });

    }
    //保存操作
    saveLabels() {
        if (this.Loading) {
            this.Loading.show()
        }
        let param = {
            buyerId: Constant.userInfo.buyerId,
            preferences: this.state.preferences,
            buyerTagParam: this.state.filtersData
        };

        HttpUtils.postRequest(HttpUrls.updateBuyerTag, param)
            .then(result => {

                let data = result.data;
                if (data) {
                    ToastToUser("保存成功")
                    DeviceEventEmitter.emit('BuyerSetLabelPage')
                    navigation.goBack()
                } else {

                    ToastToUser(result.msg ? result.msg : result.message)
                }
            })
            .catch(error => {

            }).finally(e => {

            this.Loading.hide()
        });
    }
    //选择操作
    selctOption(idx, selectIdx) {
        console.log("选择的数据", idx)
        //查询数组中的值
        let temp= this.state.filtersData
        let item = temp[idx]
        console.log('temp', item)
        let taglist = item.tagList

        //处理单选和多选
        if (item.isMultiple == 0) {
            //单选需要处理
            for (let i = 0; i < taglist.length; i++) {
                let selectItem = taglist[i]
                console.log('selectItems', selectItem)
                if(selectItem.tagValueText == '不限'){
                    taglist.forEach((it, id) => {
                        it.selected = 0
                    })
                }else {
                    taglist.map((it, id) => {
                        if(it.tagValueText == '不限'){
                            it.selected = 0
                        }
                    })
                }

                if (i == selectIdx) {
                    selectItem.selected = 1
                } else {
                    selectItem.selected = 0
                }
            }
        } else {
            //多选不要处理
            let tagItem = taglist[selectIdx]
            console.log('tagItem', tagItem)
            console.log('tagItem', item.typeText)

            if(tagItem.tagValueText == '不限'){
                taglist.forEach((it, id) => {
                    if(it.tagValueText != '不限'){
                        it.selected = 0
                    }
                })
                if(item.typeText == '车价范围'){
                    this.handleInputMinValueChange(0, idx)
                    this.handleInputMaxValueChange(0, idx)
                }
            }else {
                taglist.map((it, id) => {
                    if(it.tagValueText == '不限'){
                        it.selected = 0
                    }
                })
            }
            tagItem.selected = tagItem.selected == 1 ? 0 : 1
        }
        this.setState({
            filtersData: temp
        })
    }
    // 清空
    clearLabels(){
        let temp = this.state.filtersData
        temp.map((item, index)=>{
            if(item.type == '收车城市' || item.type == '品牌车系'){
                item.tagList = []
                item.tagList.push({
                    tagValueText: "不限",
                    tagValue: 0,
                    selected: 1
                })
            }else{
                if(item?.haveCustom == 1){
                    item.customValue['minValue'] = ''
                    item.customValue['maxValue'] = ''
                    // item.customValue['selected'] = 0
                }

                item.tagList.map((it, id)=>{
                    it.selected = 0
                    if(it.tagValueText == '不限'){
                        it.selected = 1
                    }
                })
            }

        })
        console.log('清空数据', temp)
        this.setState({
            filtersData: temp
        })
    }
    //喜好输入的值变化监听
    inputpreferences = value => {
        this.setState({ preferences: value });
    };

    //自定义值的最小值变化监听
    handleInputMinValueChange = (value, index) => {

        let temp = this.state.filtersData
        let item = temp[index]
        item.customValue.minValue = value

        this.setState({
            filtersData: temp
        })
    };

    //自定义值的最大值变化监听
    handleInputMaxValueChange = (value, index) => {
        let temp = this.state.filtersData
        let item = temp[index]
        item.customValue.maxValue = value

        this.setState({
            filtersData: temp
        })
    };

    //选项按钮布局
    optionView(data,idx) {
        return <View key={data.type} style={styles.optionsContainer}>
            {data.tagList.map((option, index) => (
                <TouchableOpacity onPress={() => {
                    console.log("点击选项")
                    this.selctOption(idx, index)
                }} key={index} style={[styles.optionButton, option.selected == 1 ? styles.selectedOption : {}]}>
                    <Text style={styles.optionText}>{option.tagValueText ? option.tagValueText : option.tagValue}</Text>
                </TouchableOpacity>
            ))}

        </View>
    }

    //城市选择组件
    //单选组件封装
    filterViews(data, idx) {
        return (
            <View style={styles.section}>
                {data.isMultiple == 0 ?
                    <Text style={styles.sectionTitle}>{data.typeText}</Text> :
                    <Text style={styles.sectionTitle}>{data.typeText} (可多选)</Text>
                }
                {/* 选项区间 */}
                {this.optionView(data,idx)}

                {/* 自定义区间 */}
                {data.customValue ?
                    <View style={styles.customPriceRange}>
                        <TouchableOpacity style={styles.customInputButton}>

                            <TextInput
                                editable={true}
                                style={styles.customInputText}
                                placeholder="自定义最小值"
                                placeholderTextColor={'#999999'}
                                value={data.customValue.minValue?data.customValue.minValue + "":""}

                                onChangeText={(text) => this.handleInputMinValueChange(text, idx)}

                            />
                        </TouchableOpacity>
                        <Text style={styles.customPriceText}>-</Text>
                        <TouchableOpacity style={styles.customInputButton}>
                            <TextInput
                                editable={true}
                                style={styles.customInputText}
                                placeholder="自定义最大值"
                                placeholderTextColor={'#999999'}
                                value={data.customValue.maxValue?data.customValue.maxValue + "":""}

                                onChangeText={(text) => this.handleInputMaxValueChange(text, idx)}
                            />

                        </TouchableOpacity>
                        <Text style={{marginLeft: 10, color: '#333'}}>万</Text>
                    </View> : null}

            </View>
        )
    }

    formatBrand(result) {
        let param = null
        let temp = this.state.filtersData
        let tagList = []
        console.log('formatBrand', result)
        temp.forEach((it, id) => {
            if (it.type === '品牌车系') {
                tagList = it.tagList
                if (result.brandId == 0 && result.seriesId == 0) {
                    param = {
                        tagValue: 0,
                        selected: 1,
                        tagValueText: "不限"
                    }
                }else if (result.brandId == 0) {
                    //不限制任何条件
                    param = {
                        tagValue: 0,
                        selected: 1,
                        tagValueText: "不限"
                    }
                } else if (result.seriesId == 0 || !result.seriesId) {
                    //车系不限
                    param = {
                        tagValue: result.brandId,
                        selected: 1,
                        tagValueText: result.brandName
                    }
                } else {
                    //精准车系
                    param = {
                        tagValue: result.seriesId,
                        selected: 1,
                        tagValueText: result.seriesName
                    }
                }
                // 选择非全部后把去除
                tagList.forEach((it, id) => {
                    // 去除tagList里面tagValue为全部的
                    if(it.tagValueText == '不限'){
                        tagList.splice(id, 1)
                    }
                })
            }
        })
        let exsits= this.filterSameData(tagList, param)
        if (!exsits) {
            tagList.push(param)
        }
        this.setState({
            filtersData: temp
        })

    }

    render() {
        navigation = this.props.navigation;
        return (

            <View style={styles.container}>
                <Header navigation={navigation} Title={'设置您的收车偏好'} />
                <View style={styles.topTitle}>
                    <Text style={{fontSize: 14, color: '#333'}}>根据您的需求，我们将为您精准推荐车源</Text>
                </View>

                <View style={styles.section}>
                     <Text style={styles.sectionTitle}>一句话描述您的收车喜好</Text>
                    {/*<TextInput*/}
                    {/*    editable={true}*/}
                    {/*    style={styles.performanceInputText}*/}
                    {/*    placeholder="一句话描述您的收车喜好"*/}
                    {/*    placeholderTextColor={'#999999'}*/}
                    {/*    value={this.state.preferences}*/}
                    {/*    onChangeText={this.inputpreferences}*/}

                    {/*/>*/}

                    <TextInput
                        style={styles.inputStyle}
                        placeholder="请描述您的投诉的内容"
                        multiline={true}
                        maxLength={30}
                        value={this.state.preferences}
                        onChangeText={(input) => {
                            this.setState({
                                textNum: input.length,
                                preferences: input
                            })
                        }}>
                    </TextInput>
                    <Text style={styles.textNum}>{this.state.textNum}/30</Text>

                </View>

                <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.scrollContent}>
                    {this.state.filtersData.map((conditions, idx) => {
                        if (conditions.type === '收车城市') {
                            {/* 收车城市 */ }
                            return <View style={styles.section}>
                                {conditions.isMultiple==1?
                                    <Text style={styles.sectionTitle}>{conditions.typeText} (可多选)</Text>:
                                    <Text style={styles.sectionTitle}>{conditions.typeText}</Text>
                                }
                                {this.optionView(conditions,idx)}
                                <TouchableOpacity onPress={() => {
                                    this.setState({
                                        showCityPicker: true
                                    })
                                }} style={styles.addButton}>
                                    <Text style={styles.addButtonText}>+ 添加城市</Text>
                                </TouchableOpacity>
                            </View>
                        }
                        else if (conditions.type === '品牌车系') {
                            {/* 精准的品牌车系 */ }
                            return <View style={styles.section}>
                                {conditions.isMultiple==1?
                                    <Text style={styles.sectionTitle}>{conditions.typeText} (可多选)</Text>:
                                    <Text style={styles.sectionTitle}>{conditions.typeText}</Text>
                                }
                                {this.optionView(conditions,idx)}
                                <TouchableOpacity onPress={() => {
                                    let params = { selectLevel: 2, from: 'BuyerSetLabelPage' }
                                    AndroidModule.selectBrand(params, (error, result) => {
                                        console.log('result = 123sd', result)
                                        this.formatBrand(result)
                                    })
                                }} style={styles.addButton}>

                                    <Text style={styles.addButtonText}>+ 添加品牌车系</Text>
                                </TouchableOpacity>
                            </View>
                        } else if (conditions.isMultiple == 0) {
                            //单选
                            return this.filterViews(conditions, idx)
                        } else if (conditions.isMultiple == 1) {
                            //多选
                            return this.filterViews(conditions, idx)
                        }

                    })}

                    <View style={{height: 70}}></View>

                </ScrollView >

                <View style={styles.buttonBox}>
                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                        this.clearLabels()
                    }} style={[styles.saveButton, {flex: 3, backgroundColor: '#F5F5F5'}]}>
                        <Text style={styles.saveButtonText}>不限</Text>
                    </TouchableOpacity>

                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                        this.saveLabels()
                    }} style={[styles.saveButton, {flex: 7, marginLeft: 10}]}>
                        <Text style={styles.saveButtonText}>保存</Text>
                    </TouchableOpacity>

                </View>

                <RegionPickerView
                    show={this.state.showCityPicker}
                    mode={'pc'}
                    hide={() => {
                        this.setState({
                            showCityPicker: false
                        })
                    }}
                    selectArea={(item) => {
                        this.cityPickerData(item)
                    }}
                />

                <Loading onRef={ref => (this.Loading = ref)} />
            </View >

        )

    }


}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        // padding: 16,
    },
    section: {
        marginBottom: 20,
        paddingHorizontal: 15,
    },
    topTitle: {
        alignItems:'center',
        backgroundColor:'#EBF5ED',
        width: '100%',
        height: 30,
        justifyContent:'center',
    },
    sectionTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        marginBottom: 10,
        marginTop:10,
        color: '#333333'
    },
    addButton: {
        borderWidth: 1,
        borderColor: '#ffcd00',
        borderRadius: 25,
        paddingVertical: 10,
        paddingHorizontal: 20,
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 8
    },
    addButtonText: {
        color: '#ffcd00',
        fontSize: 16,
    },
    optionsContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 10,
    },
    optionButton: {
        backgroundColor: '#F5F5F5',
        borderRadius: 20,
        paddingVertical: 8,
        paddingHorizontal: 16,
        margin: 5,
    },
    selectedOption: {
        backgroundColor: '#fff399',
    },
    optionText: {
        fontSize: 14,
        color: '#333333'
    },
    buttonBox: {
        flexDirection: 'row',
        flex: 1,
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        padding: 15,
        backgroundColor: '#fff',
    },
    saveButton: {
        backgroundColor: '#FFE000',
        borderRadius: 25,
        paddingVertical: 15,
        alignItems: 'center',
        justifyContent: 'center',
    },
    saveButtonText: {
        color: '#333333',
        fontSize: 14,
        fontWeight: 'bold',
    },

    customPriceRange: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 10,
    },
    customInputButton: {
        backgroundColor: '#f0f0f0',
        borderRadius: 5,
        // paddingVertical: 8,
        // paddingHorizontal: 16,
        // marginRight: 10,
    },
    customInputText: {
        fontSize: 14,
        height: 40,
        width: 120,
        textAlign: 'center',
        backgroundColor: '#F9F9F9',
        color: '#333333',
    },

    performanceInputText: {
        fontSize: 14,
        height: 40,
        backgroundColor: '#F9F9F9',
        borderRadius: 5,
        paddingLeft: 10,
        color: '#333333',
    },
    customPriceText: {
        fontSize: 14,
        color: '#333333',
    },


    inputStyle: {
        borderRadius: 5,
        height: 60,
        backgroundColor: '#F9F9F9',
        padding: 10,
        textAlignVertical: 'top',
        fontSize: 14
    },

    textNum: {
        position: 'absolute',
        right: 25,
        bottom: 10,
        fontSize: 12,
        color: '#999999'
    },

});


